﻿using System.Reflection;
using AutoMapper;
using Microsoft.Extensions.DependencyInjection;

namespace QW.Found.Extensions
{
    /// <summary>
    /// automapper构建器
    /// </summary>
    public static class AutoMapperExtensions
    {
        private static IMapper _mapper;
        /// <summary>
        /// 引用automapper
        /// </summary>
        /// <param name="services"></param>
        /// <param name="assemblies">程序集范围</param>
        public static void AddAutoMapper(this IServiceCollection services, List<Assembly> assemblies)
        {
            var mapper = AddAutoMapper(assemblies);
            services.AddSingleton<IMapper>(mapper);
            // AutoMapperUtil.SetMapper(mapper);
        }
        /// <summary>
        /// 设置映射
        /// </summary>
        /// <param name="mapper"></param>
        public static void SetMapper(IMapper mapper)
        {
            _mapper = mapper;
        }
        /// <summary>
        /// 使用Automapper
        /// </summary>
        public static Mapper AddAutoMapper(List<Assembly> assemblies)
        {
            var profiles = new List<Type>();
            foreach(var assembly in assemblies)
            {
                if(assembly.FullName.StartsWith("AutoMapper"))
                    //跳过automapper
                    continue;
                var nm_profiles = assembly.GetTypes()
                .Where(p => !p.IsInterface && !p.IsAbstract && !p.IsSealed)
                .Where(x => x != typeof(Profile) && typeof(Profile).IsAssignableFrom(x))
                .ToList();
                //加入每个命名空间下的映射配置
                profiles.AddRange(nm_profiles);
            }
            var expriseeion = new MapperConfiguration(config =>
            {
                foreach(var profile in profiles)
                    config.AddProfile(profile);
            });
            var mapper = new Mapper(expriseeion);
            SetMapper(mapper);
            return mapper;
        }
    }
}
